package com.moyun.zbmy.zizhou.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.FSubscribe;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.HomeListItem;
import com.moyun.zbmy.zizhou.beans.LiveHomeAdvance;
import com.moyun.zbmy.zizhou.beans.LiveItem;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.beans.SingleResult;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoBean;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoNewsList;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoTypeBean;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoTypeList;
import com.moyun.zbmy.zizhou.beans.Titles;
import com.moyun.zbmy.zizhou.beans.TvEntryBean;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.activities.MoreSubscriptionNoActivity;
import com.moyun.zbmy.zizhou.ui.activities.MySubscribeActivity;
import com.moyun.zbmy.zizhou.ui.activities.SearchSubscriptionNoNewsActivity;
import com.moyun.zbmy.zizhou.ui.activities.TVActivity;
import com.moyun.zbmy.zizhou.ui.adapter.NewListAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.SubscriptionNoHomeTypeAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.LiveHomeItemHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.LiveTvEntryHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.OnlyTitleHolder;
import com.moyun.zbmy.zizhou.ui.dialog.NetModeDiaFragment;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.LiveListGetHelper;
import com.moyun.zbmy.zizhou.ui.widget.BasePlayerView;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.ServerTime;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 订阅号（部门乡镇）
 */
public class SubscriptionNoFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, SubscriptionNoHomeTypeAdapter.OnHomeSubscriptionNoTypeClickListener {

    @BindView(R.id.fm_live_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;

    private String channelUrl = "sctv/bumenxiangzhen/index/bumenxiangzhen.json";
    private NewListAdapter adapter;
    private String bannerUrlTemp, newsUrlTemp, subscriptionNoUrl;
    private int pageNo = 0;
    private int pageAll = 0;
    private List<FocusColumn> subscriptionNoTypeList = new ArrayList<>();
    private List<IListShowData> dataList = new ArrayList();
    private List<SubscriptionNoTypeBean> typeList = new ArrayList();

    public SubscriptionNoFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_subscription_no, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setOnRefreshListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.autoRefresh();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden && null != recyclerView) {

        }
    }

    @Override
    public void onPause() {
        super.onPause();

    }


    @Override
    public void onLoadMore() {
        pageNo++;
        getNewsArray();
    }

    @Override
    public void onRefresh() {
        dataList.clear();
        typeList.clear();
        subscriptionNoTypeList.clear();
        pageNo = 0;
        getChannels();
    }

    /**
     * 请求基础的路径数据
     */
    private void getChannels() {
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            boolean canComplete = true;

            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                if (ListUtils.isListValued(focusColumns)) {
                    resetUrlTemps();
                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case 0:
                                    subscriptionNoTypeList.add(fc);
                                    break;
                                case 1:
                                    bannerUrlTemp = fc.getChannelUrl();
                                    break;
                                case 6:
                                    newsUrlTemp = fc.getChannelUrl();
                                    break;

                            }
                        }
                    }
                    getSubscriptionNoTypeArray();
                } else {
                    onNetFinish();
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                onNetFinish();
            }

            @Override
            public void onEnd() {
                super.onEnd();

            }
        });
    }

    /**
     * 获取 订阅号类型数据
     */
    private void getSubscriptionNoTypeArray() {
        if (ListUtils.isListValued(subscriptionNoTypeList)) {
            for (FocusColumn fc : subscriptionNoTypeList) {
                if (fc != null) {
                    SubscriptionNoTypeBean bean = new SubscriptionNoTypeBean();
                    bean.setChannelId("" + fc.getChannelId());
                    bean.setChannelName(fc.getChannelName());
                    bean.setChannelUrl(fc.getChannelUrl());
                    bean.setChannelImg(fc.getSmallImage());
                    typeList.add(bean);
                }
            }
            SubscriptionNoTypeList list = new SubscriptionNoTypeList();
            list.setWxList(typeList);
            list.setViewType(NewListAdapter.VIEWTYPE_SUBSCRIPTION_NO_TYPE);
            dataList.add(list);
        }
        getBannerArray(bannerUrlTemp);

    }

    /**
     * 获取  banner数据
     *
     * @param url
     */
    private void getBannerArray(String url) {

        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), 1) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    HomeListItem hb = new HomeListItem();
                    hb.setNewsItemList(newsItems);
                    hb.setViewType(NewListAdapter.VIEWTYPE_BANNER);
                    dataList.add(hb);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                initData();
                getNewsArray();
            }
        });
    }

    /**
     * 获取新闻列表
     */
    private void getNewsArray() {
        NetUtils.getNetAdapter().getSubscriptionNewsList(getOwnerName(), 10, pageNo, new AbsNetCallBack<SubscriptionNoNewsList>(SubscriptionNoNewsList.class) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(SubscriptionNoNewsList listVo) {
                if (null != listVo && ListUtils.isListValued(listVo.getContent())) {
                    pageAll = listVo.getTotalPages();
                    if (pageNo == 0) {
                        Titles title = new Titles();
                        title.setViewType(NewListAdapter.VIEWTYPE_SUBSCRIPTION_NO_TITLE);
                        title.setTitle("最新动态");
                        title.setShowTopDivider(1);
                        dataList.add(title);
                    }
                    for (int i = 0; i < listVo.getContent().size(); i++) {
                        listVo.getContent().get(i).setViewType(NewListAdapter.VIEWTYPE_NEWS);
                        dataList.add(listVo.getContent().get(i));
                    }

                }

            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
                initData();
            }
        });

    }

    private void initData() {
        if (null == adapter) {
            adapter = new NewListAdapter(getContext(), dataList);
            recyclerView.setAdapter(adapter);
            adapter.setSubscriptionNoTypeClickListener(this);
        } else {
            adapter.setData(dataList);
        }
    }

    private void resetUrlTemps() {
        bannerUrlTemp = null;
        newsUrlTemp = null;
        subscriptionNoUrl = null;
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(pageNo + 1 >= pageAll ? false : true);
    }

    @Override
    public void OnHomeSubscriptionNoTypeClick(int position) {
        if (ListUtils.isListValued(typeList) && typeList.size() > position) {
            SubscriptionNoTypeBean typeBean = typeList.get(position);
            if (null != typeBean) {
                Intent intent = new Intent(getContext(), MoreSubscriptionNoActivity.class);
                intent.putExtra(MoreSubscriptionNoActivity.SUBSCRIPTION_NO_TYPE_ID, typeBean.getChannelId());
                startActivity(intent);
            }
        }
    }

    @OnClick({R.id.input_key})
    protected void OnClick(View v) {
        if (v.getId() == R.id.input_key) {
            Intent intent = new Intent(getContext(), SearchSubscriptionNoNewsActivity.class);
            startActivity(intent);
        }
    }
}
